package com.dongdongshop.service.impl;

import com.dongdongshop.bo.AlipayOrderBO;
import com.dongdongshop.bo.CartBO;
import com.dongdongshop.bo.CartDetail;
import com.dongdongshop.bo.OrderBO;
import com.dongdongshop.constant.CartConstant;
import com.dongdongshop.mapper.TbOrderItemMapper;
import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.CartService;
import com.dongdongshop.service.ItemService;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.util.IdWorker;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@DubboService
public class OrderServiceImpl implements OrderService {

    @Resource
    private TbOrderMapper orderMapper;

    @Resource
    private TbOrderItemMapper orderItemMapper;

    @DubboReference
    private CartService cartService;

    @DubboReference
    private ItemService itemService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IdWorker idWorker;

    @Transactional
    @GlobalTransactional(rollbackFor = Exception.class)//添加全局事务注解
    @Override
    public AlipayOrderBO createOrder(Long userId) {
        //根据userId从redis中获取我们的购物车数据
        List<CartBO> cartBOList = cartService.getCartFromRedis(userId);
        //TODO 生成总订单号
        long outTradeNo = idWorker.nextId();
        //TODO 定义总价格
        BigDecimal sumMoney = new BigDecimal(0);
        StringBuffer orderName = new StringBuffer();
        //先扣减库存
        TbOrder order = null;
        for (CartBO cartBO : cartBOList) {
            List<CartDetail> cartDetailList = cartBO.getCartDetailList();
            order = new TbOrder();
            long orderId = idWorker.nextId();
            order.setOrderId(orderId);
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());
            order.setStatus("1");
            order.setOrderNum(String.valueOf(outTradeNo));
            order.setUserId(String.valueOf(userId));
            order.setSellerId(cartBO.getSellerId());
            for (CartDetail detail : cartDetailList) {
                TbItem item = itemService.selectItemById(detail.getItemId());
                item.setStockCount(item.getStockCount() - detail.getNum());//要减的 库存
                if (item.getStockCount() < 0) {
                    throw new RuntimeException("商品库存不足");
                }
                //更新库存
                itemService.updateStockCount(item);
                //保存orderItem表
                TbOrderItem orderItem = new TbOrderItem();
                orderItem.setOrderId(orderId);
                orderItem.setId(idWorker.nextId());
                orderItem.setItemId(detail.getItemId());
                orderItem.setGoodsId(item.getGoodsId());
                orderItem.setTitle(orderName.toString());
                orderItem.setTotalFee(detail.getTotalFee());
                orderItem.setNum(detail.getNum());
                orderItem.setOrderNum(String.valueOf(outTradeNo));
                //生成订单 将购物车数据保存到order和orderItem表中
                orderItemMapper.insertSelective(orderItem);
                //求和
                sumMoney = sumMoney.add(detail.getTotalFee());
                //添加订单名称
                orderName.append(item.getTitle());
            }
            orderMapper.insertSelective(order);

        }
        //支付宝对接订单实体返回
        AlipayOrderBO orderBO = new AlipayOrderBO();
        orderBO.setMoney(sumMoney.toString());
        orderBO.setOrderName(orderName.toString());
        orderBO.setOutTradeNo(String.valueOf(outTradeNo));
        orderBO.setGoodsDesc("测试");
        //TODO 删除购物车数据
        redisTemplate.delete(CartConstant.CART_USER+userId);
        return orderBO;
    }

    @Override
    public List<TbOrder> selectOrderBy(String out_trade_no) {
        TbOrderExample example = new TbOrderExample();
        example.createCriteria().andOrderNumEqualTo(out_trade_no);
        return orderMapper.selectByExample(example);
    }

    @Override
    public void update(String tradeNo, String s) {
        orderMapper.update(tradeNo,s);
    }

    @Override
    public void updateAll(String outTradeNo, String tradeNo) {
        orderMapper.updateAll(outTradeNo,tradeNo);
    }

    @Override
    public List<OrderBO> getAll(Long userId) {
        List<OrderBO> orderBOList = new ArrayList<>();
        TbOrderExample example = new TbOrderExample();
        example.createCriteria().andUserIdEqualTo(String.valueOf(userId));
        example.createCriteria().andStatusNotEqualTo("1");
        example.createCriteria().andStatusNotEqualTo("6");
        List<TbOrder> orderList = orderMapper.selectByExample(example);
        for(TbOrder order : orderList){
            OrderBO orderBO = new OrderBO();
            orderBO.setCreateTime(order.getCreateTime());
            orderBO.setOrderNum(order.getOrderNum());
            orderBO.setSellerId(order.getSellerId());
            TbOrderItemExample example1 = new TbOrderItemExample();
            example1.createCriteria().andOrderNumEqualTo(orderBO.getOrderNum());
            example1.createCriteria().andStatusNotEqualTo("6");
            orderBO.setItemList(orderItemMapper.selectByExample(example1));
            orderBOList.add(orderBO);
        }
        return orderBOList;
    }
}
